package com.example.mydesignmodule.yuanxing.yuanxing2;

import androidx.annotation.NonNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * @author tgw
 * @date 2021/2/25
 * @describe 深拷贝 通过 序列化的 方式
 *
 * 注意必须要继承 Serializable
 *
 * 优点 不需要 好像 Cloneable 一样实现深拷贝 需要在 clone（） 方法中对每个对象进行深拷贝
 *
 * 推荐使用
 */
public class DeepShape  implements Serializable {


    private ArrayList<String> arrayList = new ArrayList<>();
    private String name;
    private String age;
    private String copy;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getCopy() {
        return copy;
    }

    public void setCopy(String copy) {
        this.copy = copy;
    }

    public ArrayList<String> getArrayList() {
        return arrayList;
    }

    public void setArrayList(String s) {
        this.arrayList.add(s);
    }

    @Override
    public String toString() {
        return "Shape{" +
                "arrayList=" + arrayList.toString() +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", copy='" + copy + '\'' +
                '}';
    }

    public DeepShape deepCopy() {
        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;


        try {
            //创建序列化 流
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //将当前对象以对象流的方式输出
            oos.writeObject(this);
            //创建反序列化 流
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            return (DeepShape) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                bis.close();
                oos.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


}
